package com.xhb.ui.tools;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.xml.bind.DatatypeConverter;

import org.apache.commons.lang3.StringUtils;

import com.teamdev.jxbrowser.js.JsAccessible;
import com.xhb.ui.http.HttpServer;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;

public   class Tools {
	
	  public static Integer VIDEO_CHCHE_COUNT=0;

	  @JsAccessible // This public method is accessible from JS.
      public void createDir(String name) throws IOException {
		  File file=new File(name);
		  if(!file.exists()) {
			  file.mkdir();
		  }
      }
	 
	  @JsAccessible // This public method is accessible from JS.
      public void dwonPic(String dir,String httpURL) throws IOException {
		  HttpUtil.downloadFile(httpURL, new File(dir +"//" +httpURL.split("/")[httpURL.split("/").length-1]));
      }
	  
	  @JsAccessible // This public method is accessible from JS.
      public void dwonPicHead(String dir,String httpURL) throws IOException {
		  HttpUtil.downloadFile(httpURL, new File(dir +"//head.jpg"));
      }
	  
	  
		@JsAccessible // This public method is accessible from JS.
		public String dwonBase64(String filePath) throws IOException {
			String data = HttpUtil.get(filePath);
			return data;
		}
	  
	  @JsAccessible // This public method is accessible from JS.
      public String getCount(String dir) throws IOException {
		  File countFile=new File(dir+"//count.conf");
		  if(countFile.exists()) {
			  String count= FileUtil.readString(countFile,"utf-8");
			  Integer c=Integer.parseInt(count)+1;
			  FileUtil.writeString(c.toString(), countFile, "utf-8");
			  return c.toString();
		  }
		  else {
			  FileUtil.writeString("1", countFile, "utf-8");
			  return "1";
		  }
      }
	  
	  
	  @JsAccessible // This public method is accessible from JS.
      public String getVideoUrl(String countLong) throws IOException {
		  File countLongCacheFile=new File(HttpServer.BASE_PATH+"//课程视频//"+countLong.replace(":", "")+".mp3");
		  if(countLongCacheFile.exists()) {
			  // 读取文件内容到字节数组中
		        byte[] bytes = FileUtil.readBytes(countLongCacheFile);
		        // 使用 Base64 编码器将字节数组转换为 Base64 字符串
		        String base64String = Base64.getEncoder().encodeToString(bytes);
		        return "data:audio/mpeg;base64,"+base64String;
		  }
		  return "";
      }
	  
	  
		@JsAccessible // This public method is accessible from JS.
		public String saveFile(String dir, String base64, String currentVId, Integer count) throws IOException {
			try {
				String imgDir = "";
				if (StringUtils.contains(currentVId, "error")) {
					imgDir = "/errorImg";
				} else {
					imgDir = "/successImg";
				}
				File file = new File(dir + imgDir);
				if (!file.exists()) {
					file.mkdirs();
				}
				BufferedImage image;
				byte[] imageByte;
				imageByte = DatatypeConverter.parseBase64Binary(base64);
				ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
				image = ImageIO.read(new ByteArrayInputStream(imageByte));
				bis.close();

				String time = LocalDateTimeUtil.format(LocalDateTime.now(), DatePattern.NORM_DATETIME_PATTERN);

				File outputFile = new File(file.getPath() + "/" + currentVId + "_"
						+ time.replace("-", "").replace(":", "") + "_" + count + ".png");
				if (!outputFile.exists()) {
					outputFile.createNewFile();
				}
				ImageIO.write(image, "png", outputFile);
				return "1";
			} catch (IOException e) {
				e.printStackTrace();
				return "0";
			}
		}
	  
		/**
		 * 上传题目
		 * 
		 * @param subectjs liyixing
		 * @throws UnsupportedEncodingException 
		 */
		@JsAccessible
		public String uploadSubject(String subectjs) throws UnsupportedEncodingException {
			{
				LogFormat.info(subectjs);
			}
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("subjects", subectjs);
			try {

				String result = HttpUtil.post("http://47.102.205.5:8082/zyk/save_subject.jhtml?format=json",params);

				Map<String, Object> map = JSONUtil.parseObj(result);
				List<String> s = (List<String>) map.get("errors");

				if (s == null || s.isEmpty()) {
					return JSONUtil.toJsonStr(map.get("rights"));
				} else {
					return "0";
				}
			} catch (Exception e) {
				LogFormat.info(e.getMessage());
				return "0";
			} finally {
			}
		}
		
		public static void main(String [] args) throws UnsupportedEncodingException {
			String sbuject=" [{\"answers\":[\"20\",\"22\",\"24\",\"28\"],\"content\":\"《劳动合同法》规定：非全日制用工，是指以小时计酬为主，劳动者在同一用人单位一般平均每日工作时间不超过4小时，每周工作时间累计不超过（  ）小时。\",\"analysis\":\"《劳动合同法》第六十八条规定：非全日制用工，是指以小时计酬为主，劳动者在同一用人单位一般平均每日工作时间不超过4小时，每周工作时间累计不超过24小时。\"},{\"answers\":[\"等级为A\",\"等级为A1\",\"等级为B\",\"等级为B1\"],\"content\":\"下列关于办公用房、宿舍的防火设计建筑构件的燃烧等级的说法正确的是（    ）。\",\"analysis\":\"建筑构件的燃烧性能等级应为A级，当采用金属夹芯板材时，其芯材的燃烧性能等级应为A级\"}]";
			Tools tools=new Tools();
			tools.uploadSubject(sbuject);
		}
}